package com.hz.friends.fragment.contacts;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVGeoPoint;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.hz.friends.activity.AddFriendsActivity;
import com.hz.friends.activity.MaintabsActivity;
import com.hz.friends.activity.R;
import com.hz.friends.activity.UserInfosActivity;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.serverrequest.ALEngineConfig.ALUserGender;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

public class FriendContacts {
	private Context mcontext;
	private PullToRefreshListView mlistview;
	private int type = -3; // 0:my fans 1:my concren 2:black list -1:搜索 3:nearby
	private final int limit = 100;// 分页
	private int skip = 0;// 跳过记录条数
	private String TAG = "FriendContacts";
	private FriendAdpter madpter;
	private AQuery aq;
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	private double lat = 0;
	private double lon = 0;
	private ALUserGender userGender = ALUserGender.ALUserGenderOfUndefine;
	private List<AVUser> followerList = null;  //我的粉丝
	private List<AVUser> followeeList = null; //我关注的
	private List<AVUser> followeeSpecialList = null; //我特别关注的
	private List<AVUser> followeeAndFollowerList = null; //我关注的关注我的
//	private String searchkey = null;
	
	

	public FriendContacts(PullToRefreshListView mlistview, Context mcontext,
			int type) {
		this.mcontext = mcontext;
		this.mlistview = mlistview;
		this.type = type;
		init();
		initEvents();
		if (type != -1)
			onRefresh();
	}

	public FriendContacts(PullToRefreshListView mlistview, Context mcontext){
		this.mcontext = mcontext;
		this.mlistview = mlistview;
		init();
		initEvents();
	}
	
 
	
	//设置页面类别
	public void setType(int type) {
		this.type = type;
	}
	
	public int getType(){
		return type;
	}


	public void setLocation(double lat, double lon) {
		this.lat = lat;
		this.lon = lon;
	}
	
	public FriendContacts(PullToRefreshListView mlistview, Context mcontext,
			int type,double lat,double lon,ALUserGender userGender) {
		this.mcontext = mcontext;
		this.mlistview = mlistview;
		this.type = type;
		this.lat = lat;
		this.lon = lon;
		this.userGender = userGender;
		init();
		initEvents();
		if (type != -1)
			onRefresh();
	}
	public void setUserGender(ALUserGender userGender){
	     this.userGender = userGender;	
	}

	private void init() {
		if(madpter == null)
		madpter = new FriendAdpter();
		mlistview.setAdapter(madpter);
		if(aq == null)
		aq = new AQuery(mcontext);
	}

	private void initEvents() {
		mlistview.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				onLoadMore();
			}

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				onRefresh();
			}
		});
	}

	private void onLoadMore() {
		switch (type) {
		case 0:
			uploadFriends1();
			break;
		case 1:
			uploadFriends2();
			break;
		case 2:
			uploadFriends3();
			break;
		default:
			break;
		}
	}

	private void onRefresh() {
		if(type == -1){//搜索
			mlistview.onRefreshComplete();
			return;
		}
		
//		madpter.clearData();
//		madpter.notifyDataSetChanged();
		skip = 0;
		switch (type) {
		case 0:
			uploadFriends1();
			break;
		case 1:
			uploadFriends2();
			break;
		case 2:
			uploadFriends3();
			break;
		case 3:
			uploadNearbyusers();
			break;
		default:
			break;
		}
	}

	public void loadUserlist() {
		MLog.i(TAG, "loadUserlist type:"+type);
		init();
		initEvents();
		switch (type) {
		case 0:
			if(followerList != null){
				madpter.setData(followerList);
				madpter.notifyDataSetChanged();
			}else{
				onRefresh();
			}
			break;
		case 1:
			if(followeeList != null){
				madpter.setData(followeeList);
				madpter.setSpecialData(followeeSpecialList);
				madpter.notifyDataSetChanged();
			}else{
				onRefresh();
			}
			break;
		case 2:
			if(followeeAndFollowerList != null){
				madpter.setData(followeeAndFollowerList);
				madpter.notifyDataSetChanged();
			}else{
				onRefresh();
			}
			break;
//		case 3:
//			uploadNearbyusers();
//			break;
		default:
			break;
		}
	}
	
	
	// 我的粉丝
	private void uploadFriends1() {
		ALUserEngine.defauleEngine().getFollowerList(AVUser.getCurrentUser(),
				limit, skip, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadFriends1 avexception:" + avexception
								+ "  object:" + object);
						mlistview.onRefreshComplete();
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							 followerList = data;
							if (data == null || data.size() == 0) {
//								if (madpter.getCount() == 0) {
//									// ((MaintabsActivity) mcontext)
//									// .showSysToast("没有好友");
//								} else
//									((MaintabsActivity) mcontext)
//											.showSysToast("没有更多");
							} else {
								followerList = data;
								skip = skip + data.size();
								madpter.setData(data);
								madpter.notifyDataSetChanged();
							}
							if(followerList == null){
								followerList = new ArrayList<AVUser>();
							}
						} else {
							avexception.printStackTrace();
//							((MaintabsActivity) mcontext).showSysToast("请求失败");
						}

					}
				});

	}

	// 我的关注
	private void uploadFriends2() {
		ALUserEngine.defauleEngine().getFolloweeList(AVUser.getCurrentUser(),
				limit, skip, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {

						MLog.i(TAG, "getFolloweeList avexception:"
								+ avexception + "  object:" + object);

						mlistview.onRefreshComplete();
						if (avexception == null) {
							HashMap<String, List> map = (HashMap<String, List>) object;
							if (map == null) {
 
								//保存数据
								if(followeeList == null){
									followeeList = new ArrayList<AVUser>();
								}else{
									followeeList.clear();
								}
								
								return;
							}
							List<AVUser> data = map.get("followees");
							List<AVUser> specialsdata = map.get("specials");
							
							skip = skip + data.size();
							madpter.setData(data);
							madpter.setSpecialData(specialsdata);
							madpter.notifyDataSetChanged();
							
							//保存数据
							if(followeeList == null){
								followeeList = new ArrayList<AVUser>();
							}else{
								followeeList.clear();
							}
							if(data != null)
							followeeList.addAll(data);
						} else {
							avexception.printStackTrace();
//							((MaintabsActivity) mcontext).showSysToast("请求错误");
						}

					}
				});
	}

	// 互粉
	private void uploadFriends3() {
		ALUserEngine.defauleEngine().getFolloweeAndFollowerList(
				AVUser.getCurrentUser(), limit, skip, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadFriends3 avexception:" + avexception
								+ "  object:" + object);
						mlistview.onRefreshComplete();
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							followeeAndFollowerList = data;
							if (data == null || data.size() == 0) {
//								if (madpter.getCount() == 0) {
//									// ((MaintabsActivity) mcontext)
//									// .showSysToast("没有好友");
//								} else
//									((MaintabsActivity) mcontext)
//											.showSysToast("没有更多");
							} else {
								skip = skip + data.size();
								madpter.setData(data);
								madpter.notifyDataSetChanged();
							}
							//初始化
							if(followeeAndFollowerList == null){
								followeeAndFollowerList = new ArrayList<AVUser>();
							}
						} else {
							avexception.printStackTrace();
//							((MaintabsActivity) mcontext).showSysToast("请求错误");
						}

					}
				});

	}

	public void onSearch(String text) {
		init();
		initEvents();
		
		ArrayList<String> keys = new ArrayList<String>();
		keys.add(text);
		ALUserEngine.defauleEngine().searchUserByMyFollowWithNickname(keys, 20,
				null, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "onSearch avexception:" + avexception
								+ "  object:" + object);
						mlistview.onRefreshComplete();
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							if (data == null || data.size() == 0)
								((MaintabsActivity) mcontext)
										.showSysToast("没有搜索到用户");
							madpter.setData(data);
							madpter.notifyDataSetChanged();
						} else {
							avexception.printStackTrace();
							((MaintabsActivity) mcontext).showSysToast("搜索失败");
						}
					}
				});

	}

	// onSearchs 搜索附近的用户
	private void uploadNearbyusers() {
		MLog.i(TAG, "uploadNearbyusers  lat:" + lat + "  lon:" + lon);
		ALUserEngine.defauleEngine().searchUserWithNear(lat, lon, 1000,
				userGender, limit,
				new ArrayList<AVUser>(), new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "uploadNearbyusers avexception:"
								+ avexception + "  object:" + object);
						mlistview.onRefreshComplete();
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							// if (data == null || data.size() == 0)
							// ((MaintabsActivity) mcontext)
							// .showSysToast("没有搜索到用户");
							madpter.setData(data);
							madpter.notifyDataSetChanged();
						} else {
							avexception.printStackTrace();
							// ((MaintabsActivity)
							// mcontext).showSysToast("搜索错误");
						}

					}
				});
	}
	   private ImageView palyingImageView = null;
	/**
	 * @Description
	 * @param name
	 */
	private void playMusic(final String url, final ImageView iv_voice) {
		try {
			synchronized (mMediaPlayer) {// 清除上条消息的状态
				if (mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
					if (palyingImageView != null) {
						AnimationDrawable lastvoiceAnimation = (AnimationDrawable) palyingImageView
								.getDrawable();
						if (lastvoiceAnimation != null)
							lastvoiceAnimation.stop();
						palyingImageView.setVisibility(View.INVISIBLE);
					}
				}
				iv_voice.setVisibility(View.VISIBLE);
				final AnimationDrawable voiceAnimation = (AnimationDrawable) iv_voice
						.getDrawable();
				mMediaPlayer.reset();
				mMediaPlayer.setDataSource(url);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
				voiceAnimation.start();
				palyingImageView = iv_voice;
				mMediaPlayer
						.setOnCompletionListener(new OnCompletionListener() {
							public void onCompletion(MediaPlayer mp) {
								voiceAnimation.stop();
								iv_voice.setVisibility(View.INVISIBLE);
							}
						});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	class FriendAdpter extends BaseAdapter {
		private List<AVUser> userlist = new ArrayList<AVUser>();
		private List<AVUser> specialuserlist = new ArrayList<AVUser>();

		@Override
		public int getCount() {
			return userlist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		public void setData(List<AVUser> userlist) {
			if (userlist == null)
				userlist = new ArrayList<AVUser>();
			this.userlist = userlist;

		}



		public void setSpecialData(List<AVUser> userlist){
			if (userlist == null)
				userlist = new ArrayList<AVUser>();
			this.specialuserlist = userlist;
			//保存数据
			if(followeeSpecialList == null){
				followeeSpecialList = new ArrayList<AVUser>();
			}else{
				followeeSpecialList.clear();
			}
			followeeSpecialList.addAll(userlist);
		}
		
		public void clearData() {
			this.userlist.clear();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			convertView =  null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(mcontext).inflate(
						R.layout.adpter_friendcontacts, null);
				// holder = new ViewHolder();
				holder.imv_heard = (ImageView) convertView
						.findViewById(R.id.imv_heard);
				holder.txv_name = (TextView) convertView
						.findViewById(R.id.txv_name);
				holder.layout_special = (LinearLayout) convertView
						.findViewById(R.id.layout_special);
				holder.imv_special = (ImageView) convertView
						.findViewById(R.id.imv_special);
				holder.txv_special = (TextView) convertView
						.findViewById(R.id.txv_special);
				holder.layoutxx = (LinearLayout) convertView
						.findViewById(R.id.layoutxx);
				holder.txv_signature = (TextView) convertView
						.findViewById(R.id.txv_signature);
				holder.layout_sex = (LinearLayout) convertView
						.findViewById(R.id.layout_sex);
				holder.imv_sex = (ImageView) convertView
						.findViewById(R.id.imv_sex);
				holder.txv_age = (TextView) convertView
						.findViewById(R.id.txv_age);
				holder.layout_voice = (LinearLayout) convertView
						.findViewById(R.id.layout_voice);
				holder.txv_voiceduration = (TextView) convertView
						.findViewById(R.id.txv_voiceduration);
				holder.imv_speakanim = (ImageView) convertView
						.findViewById(R.id.imv_speakanim);
				holder.txv_durationkm = (TextView) convertView
						.findViewById(R.id.txv_durationkm);
				holder.txv_timeafter = (TextView) convertView
						.findViewById(R.id.txv_timeafter);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			final AVUser avuser = userlist.get(position);
			String name = avuser.getUsername();
			final String nickname = avuser.getString("nickname");
			String heardurl = avuser.getString("headViewURL");
			String signature = avuser.getString("signature");
			if(TextUtils.isEmpty(signature))
				signature ="No content";
			Date brithday = avuser.getDate("brithday");
			int gender = avuser.getInt("gender");
			int introductionOfVoiceOfDuration = avuser
					.getInt("introductionOfVoiceOfDuration");
			final String introductionOfVoiceURL = avuser
					.getString("introductionOfVoiceURL");
			//距离
			AVGeoPoint togeopoint = avuser.getAVGeoPoint("location");
			 Date togeopointdate = avuser.getDate("lastUpdateLocationDate");

			final int width = DensityUtil.dip2px(mcontext, 70);
			// default image
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					mcontext, crclebitmap, width, 1, "#eeeeee");
			holder.imv_heard.setBackgroundDrawable(new BitmapDrawable(crclestrokebitmap));

//			aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {
//				@Override
//				public void callback(String url, Bitmap bitmap,
//						AjaxStatus status) {
//					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(mcontext,
//							bitmap, width, 1, "#eeeeee");
//					holder.imv_heard.setImageBitmap(mbitmap);
//				}
//			});
			aq.id(holder.imv_heard).image(heardurl,true,true,width,0,new BitmapAjaxCallback(){
				@Override
				protected void callback(String url, ImageView iv, Bitmap bm,
						AjaxStatus status) {
					super.callback(url, iv, bm, status);
					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(mcontext,
							bm, width, 1, "#eeeeee");
					holder.imv_heard.setImageBitmap(mbitmap);
					holder.imv_heard.setBackgroundColor(Color.TRANSPARENT);
				}
			});
			
			holder.txv_name.setText(nickname);
			holder.txv_signature.setText(signature);
			holder.txv_age.setText(String.valueOf(UtilTools
					.getAgeByBirthday(brithday))); // 年龄
			holder.imv_heard.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					((CustomApplication) ((Activity) mcontext).getApplication()).user = avuser;
					Bundle bundle = new Bundle();
					bundle.putInt("isother", 1);
					Intent intent = new Intent(mcontext,
							UserInfosActivity.class);
					intent.putExtras(bundle);
					mcontext.startActivity(intent);
				}
			});
			holder.layoutxx.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					CustomApplication.getInstance().user = avuser;
					Intent intent = new Intent(mcontext,
							GroupChatActivity.class);
					intent.putExtra("titlename", nickname);
					intent.putExtra("isGroup", false);
					mcontext.startActivity(intent);
				}
			});
			holder.layout_special.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					addFriend(avuser, holder.layout_special,
							holder.imv_special, holder.txv_special);
				}
			});
			if (gender == ALUserGender.ALUserGenderOfFemale.get_value()) {// 女性
				holder.layout_sex
						.setBackgroundResource(R.drawable.shape_bj_icwoman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_woman);
			} else {// 男性
				holder.layout_sex
						.setBackgroundResource(R.drawable.shape_bj_icman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_man);
			}

			getAttenState(avuser, holder.layout_special, holder.imv_special,
					holder.txv_special);

			// 语音
			if (introductionOfVoiceOfDuration > 0) {
				holder.layout_voice.setVisibility(View.VISIBLE);
				holder.txv_voiceduration.setText(String
						.valueOf(introductionOfVoiceOfDuration) + "\'\'");
				holder.txv_voiceduration.setTag(introductionOfVoiceURL);
			} else {
				holder.layout_voice.setVisibility(View.INVISIBLE);
			}

			holder.layout_voice.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					playMusic(introductionOfVoiceURL, holder.imv_speakanim);
				}
			});

			setDistance(togeopoint, holder.txv_durationkm);
			if(togeopointdate != null){
				holder.txv_timeafter.setText(UtilTools.getdurtionTimeFormat(togeopointdate, new Date()));
			}else{
				holder.txv_timeafter.setText("no time");
			}
			
			return convertView;
		}
		private void setDistance(AVGeoPoint togeopoint,TextView txv) {
			AVGeoPoint mgeopoint = AVUser.getCurrentUser().getAVGeoPoint("location");
			if(mgeopoint == null || togeopoint == null){
				txv.setText("unknow");
				return;
			}
			double distan = mgeopoint.distanceInKilometersTo(togeopoint);
			  DecimalFormat  df = new DecimalFormat("#.##");
				double km = distan/1000;
			   txv.setText(df.format(km)+" km");
			
		}
		private void addFriend(AVUser avuser, final LinearLayout layout,
				final ImageView imv, final TextView txv) {
			if (layout.getTag() != null){//取消特别关注
				ALUserEngine.defauleEngine().updateSpecialFollowToFollow(avuser,
						new CallBack() {

							@Override
							public void done(Object object, AVException avexception) {
								if (avexception == null) {
									((MaintabsActivity) mcontext)
											.showSysToast("取消特别关注成功");
									layout.setBackgroundResource(R.drawable.shape_nearby_attention_grey);
									layout.setTag(null);
								} else {
									((MaintabsActivity) mcontext)
											.showSysToast("取消特别关注失败");
									avexception.printStackTrace();
								}
							}
						});	
			}else{//添加特别关注
				ALUserEngine.defauleEngine().updateFollowToSpecialFollow(avuser,
						new CallBack() {

							@Override
							public void done(Object object, AVException avexception) {
								if (avexception == null) {
									((MaintabsActivity) mcontext)
											.showSysToast("特别关注成功");
									layout.setBackgroundResource(R.drawable.shape_nearby_attention);
//									imv.setImageResource(R.drawable.contact_special_green);
//									txv.setTextColor(Color.parseColor("#52c43c"));
									layout.setTag("1");
								} else {
									((MaintabsActivity) mcontext)
											.showSysToast("特别关注失败");
									avexception.printStackTrace();
								}
							}
						});	
			}
	

		}

		private void getAttenState(AVUser avuser, final LinearLayout layout,
				ImageView imv, TextView txv) {
			for (int i = 0; i < this.specialuserlist.size(); i++) {
				AVUser user = this.specialuserlist.get(i);
				if (avuser.getObjectId().equals(user.getObjectId())) {
//					layout.setBackgroundColor(color.transparent);
//					imv.setImageResource(R.drawable.contact_special_green);
//					txv.setTextColor(Color.parseColor("#52c43c"));
					layout.setBackgroundResource(R.drawable.shape_nearby_attention);
					layout.setTag("1");
					return;
				}
			}

//			layout.setBackgroundResource(R.drawable.shape_nearby_attention);
//			imv.setImageResource(R.drawable.contact_special_wither);
//			txv.setTextColor(Color.parseColor("#ffffff"));
			layout.setTag(null);
			layout.setBackgroundResource(R.drawable.shape_nearby_attention_grey);

		}

	}

	private static class ViewHolder {
		ImageView imv_heard; //
		TextView txv_name;//
		LinearLayout layoutxx;
		LinearLayout layout_special;
		ImageView imv_special;
		TextView txv_special;
		TextView txv_signature; // 签名
		LinearLayout layout_sex; // 性别布局
		ImageView imv_sex; // 性别图标
		TextView txv_age; // 年龄
		LinearLayout layout_voice;// 声音
		TextView txv_voiceduration; // 声音
		ImageView imv_speakanim; // 声音动画
		TextView txv_durationkm; // 声音
		TextView txv_timeafter; // 声音

	}
	
	private void setDistance(double mi, TextView txv) {
		DecimalFormat df = new DecimalFormat("#.###");
		double km = mi / 1000;
		txv.setText(df.format(km) + " km");

	}
	
}
